import axios from 'axios'
import * as qs from 'qs'
export default class Http {
  constructor (defaults) {
    this._http = axios.create(defaults)
    // 添加请求拦截器
    this._http.interceptors.request.use(async(config = {}) => {
      this.$before_request && await this.$before_request(config)
      return config
    }, async (error) => {
      this.$request_failed && await this.$request_failed(error)
      return Promise.reject(error)
    })
    // 添加响应拦截器
    this._http.interceptors.response.use(async(response) => {
      this.$after_response && await this.$after_response(response)
      return response.data
    }, async (error) => {
      this.$response_failed && await this.$response_failed(error)
      return Promise.reject(error)
    })
  }

  method (method) {
    return (url, data = {}, requestConfig = {}) => {
      let opt = {
        method,
        url
      }
      opt = Object.assign(opt, requestConfig)
      switch (method) {
        case 'get':
          opt.params = data
          if (this._http.defaults.headers[method]['Content-Type'] === 'application/x-www-form-urlencoded') {
            opt.params = qs.stringify(opt.params)
          }
          break
        default:
          opt.data = data
          if (this._http.defaults.headers[method]['Content-Type'] === 'application/x-www-form-urlencoded') {
            opt.data = qs.stringify(opt.data)
          }
          break
      }
      return this._http(opt)
    }
  }
  get = this.method('get')
  del = this.method('delete')
  post = this.method('post')
  put = this.method('put')
  patch = this.method('patch')
}
